package com.fs.ssm004.realm;

import com.fs.ssm004.pojo.Permission;
import com.fs.ssm004.pojo.Role;
import com.fs.ssm004.pojo.Teacher;
import com.fs.ssm004.service.TeacherService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class MyShiroRealm extends AuthorizingRealm {
    @Autowired
    private TeacherService teacherService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //拿到要认证的用户的用户账号
        String teacherName = (String) authenticationToken.getPrincipal();
        //根据要认证的用户账号去系统查询相关用户信息
        Teacher teacher = teacherService.getOneByTeachername(teacherName);

        if (teacher == null){
            throw new UnknownAccountException(teacher.getName()+"没有查到这位老师信息");
        }
        //获取当前用户会话域
        Session session = SecurityUtils.getSubject().getSession();
        //在会话域中保存这个用户
        session.setAttribute("teacher",teacher);

        String password = teacher.getPassword();
        String realName = this.getName();
       /* ByteSource byteSource = ByteSource.Util.bytes(teacher.getTeacherName());*/
        //构造认证信息，使用账号，密码
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(teacherName, password,/*byteSource,*/realName);
        return info;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //拿到待授权的用户账号
        String  teacherName =(String) principalCollection.getPrimaryPrincipal();
        //根据待授权的老师账号去系统查询相关用户授权信息
        Teacher teacher = teacherService.getOneByTeachername(teacherName);
       /* Set<String> roles = new HashSet<>();
        Set<String> permissions = new HashSet<>();
        //收集user的权限信息
        for (Role role : teacher.getRoles()) {
            roles.add(role.getName());
            //收集user的权限信息
            if (role.getPermissions() != null){
                for (Permission permission : role.getPermissions()) {
                    permissions.add(permission.getName());
                }
            }
        }
        //创建一个授权信息对象，用来收集用户的角色信息和授权信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roles);
        info.addStringPermissions(permissions);*/

        return null;
    }

}
